/**
 * Copyright (c) 2011, UNC-Chapel Hill

   All rights reserved.

   Redistribution and use in source and binary forms, with or without modification, are permitted provided 
   that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and 
    * the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the 
    * following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the UNC-Chapel Hill nor the names of its contributors may be used to endorse or promote 
    * products derived from this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
   STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
   ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package edu.unc.ils.biosis.parser;

import java.io.BufferedReader;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class BIOSISRecord 
{
	Map<String, List<String>> fieldMap = new HashMap<String, List<String>>();
	
	/* UT BIOSIS Accession Number */
	String accessionNumber;
	

	protected String getFirstValue(BIOSISFields field) {
		List<String> values =  fieldMap.get(field.getFieldName());
		if (values != null)
			return values.get(0);
		else 
			return null;
	}
	public String getAccessionNumber() {
		return getFirstValue(BIOSISFields.ACCESSION_NUMBER).replace("BIOSIS:", "");
	}

	public String getTitle() {
		return getFirstValue(BIOSISFields.TITLE);
	}


	public List<String> getAuthors() {
		return fieldMap.get(BIOSISFields.AUTHOR);
	}

	public String getSource() {
		return getFirstValue(BIOSISFields.SOURCE);
	}


	public String getAbstr() {
		return getFirstValue(BIOSISFields.ABSTRACT);
	}

	public String getISSN() {
		return getFirstValue(BIOSISFields.ISSN);
	}


	public String getDOI() {
		return getFirstValue(BIOSISFields.DOI);
	}


	public List<String> getMajorConcepts() {
		List<String> majorConcepts = new ArrayList<String>();
		
		String conceptString = getFirstValue(BIOSISFields.MAJOR_CONCEPT);
		if (conceptString != null)
		{
			String[] mcs = conceptString.split(";");
			for (String mc: mcs)
				majorConcepts.add(mc.trim());
		}
		return majorConcepts;
	}


	public List<String[]> getConceptCodes() {
		List<String[]> conceptCodes = new ArrayList<String[]>();
		String conceptString = getFirstValue(BIOSISFields.CONCEPT_CODE);
		if (conceptString != null)
		{
			String[] ccs = conceptString.split(";");
			for (String cc: ccs)
			{
				cc = cc.trim();
				String code = cc.substring(0, cc.indexOf(","));
				String value = cc.substring(cc.indexOf(",")+1, cc.length());
				conceptCodes.add(new String[]{code.trim(), value.trim()});
			}
		}
		return conceptCodes;
	}


	public List<BIOSISTaxonomicData> getTaxonData() 
	{
		List<BIOSISTaxonomicData> taxons = new ArrayList<BIOSISTaxonomicData>();
		/*
		 TA Vertebrata, Chordata, Animalia; Animals, Chordates, Nonhuman
		    Vertebrates, Reptiles, Vertebrates; Reptilia [85400]; [Diplodocus
		    carnegii; (Fossil)] [Brachiosaurus]/Chordata, Animalia; Animals,
		    Chordates, Nonhuman Vertebrates, Vertebrates; Vertebrata [85150];
		    [Xenoposeidon prononeukos; neosauropod; (Fossil)]
		*/
		/* 
		 TA Artiodactyla, Mammalia, Vertebrata, Chordata, Animalia; Animals,
  			Artiodactyls, Chordates, Mammals, Nonhuman Vertebrates, Nonhuman
  			Mammals, Vertebrates; Bovidae [85715]; [Hippotragus niger; sable
  			antelope] [Pantholops hodgsoni; chiru] [Ovis vignei; urial sheep]
		 */
		String text = getFirstValue(BIOSISFields.TAXONOMIC_NAME);
		if (text != null)
		{
			String[] rows = text.split("\\/");
			for (String row: rows) 
			{
				BIOSISTaxonomicData taxonData = new BIOSISTaxonomicData();
				
				// Field 1 - beginning of string to first ;
				int fieldStart = 0;
				int fieldEnd = row.indexOf(";");
				
				// Super Taxa (Lowest to highest)
				String superTaxa = row.substring(fieldStart, fieldEnd);
				fieldStart = fieldEnd + 1;
				fieldEnd = row.indexOf(";", fieldStart);
				superTaxa = superTaxa.trim();
				String[] superTaxaList = superTaxa.split(",");
				taxonData.setSuperTaxa(superTaxaList);
			
				// Taxa Notes  (Common names discussed by author)
				String taxaNotes = row.substring(fieldStart, fieldEnd);
				fieldStart = fieldEnd + 1;
				fieldEnd = row.indexOf(";", fieldStart);
				taxaNotes = taxaNotes.trim();
				taxonData.setTaxaNotes(taxaNotes);
				
				// Organism Classifier [Biosystematic Code]: Represents the organism classifier and the corresponding 
				// Biosystematic Code for an organism discussed in the source document by the author. 
				// The code may be followed by an asterisk (*), which is used to indicate the reporting of a 
				// new Taxon within the source document. In some instances, the asterisk may be replaced with -NEW.
				String classifier = row.substring(fieldStart, fieldEnd);
				fieldStart = fieldEnd + 1;
				classifier = classifier.trim();
				String classifierName = classifier.substring(0, classifier.indexOf("["));
				String classifierCode = classifier.substring(classifier.indexOf("[")+1, classifier.indexOf("]"));
				taxonData.setClassifierName(classifierName.trim());
				taxonData.setClassifierCode(classifierCode.trim());
				
				// The Organism Name contains the name of an organism as given by the author(s) in the source document
				String variants = row.substring(fieldStart, row.length());
				fieldStart = 0;
				while ((fieldEnd = variants.indexOf("]", fieldStart)) > 0)
				{
					// Variant: A variant name for the organism. The variant may be a corrected spelling (from the author) 
					// or another common or species name.
					
					String variantDetails = variants.substring(fieldStart + 2, fieldEnd);
					fieldStart = fieldEnd + 1;
					
					// Details: Other information such as gender of the organism, its developmental stage, and its role. 
					// It may also contain a fossil indicator and whether the organism is a new Taxon and its type.
					String[] fields = variantDetails.split(";");
					String details = "";
					String variant = "";
					if (fields.length >=1)
						 variant = fields[0];
					if (fields.length ==2)
						details = fields[1];
					taxonData.addVariant(variant, details);
				}
				taxons.add(taxonData);
			}
		}
		return taxons;
	}


	public List<String> getGeographicData() {
		List<String> areas = new ArrayList<String>();
		/*
		 * Term	Geopolitical Terms	Zoogeographical Region
			GE California; USA, North America; Nearctic region/North Carolina; USA,
			  North America; Nearctic region

			GE Africa; Ethiopian region/Antarctica; Antarctic Region/Europe;
			  Palearctic region/New Zealand; Australasian region/South America;
			  Neotropical region/Tasmania; Australia; Australasian region

			GE Central America; Neotropical region/Mexico; North America; Nearctic
			  region/Neotropical region; Neotropical region/North America; Nearctic
			  region
			  
			GE Africa; Ethiopian region/Australia; Australasian region/Gondwana;
			  India, Asia; Oriental region

		 */
		String text = getFirstValue(BIOSISFields.GEOGRAPHIC_AREA);
		if (text != null)
		{
			String[] rows = text.split("\\/");
			for (String row: rows) 
				areas.add(row);
		}
		return areas;
	}

	public List<String> getGeologicData() {
		List<String> areas = new ArrayList<String>();
		/*
			TM Paleozoic; Phanerozoic
			TM Paleozoic; Paleozoic
			TM Archean/Cretaceous/Mesozoic/Oligocene/Tertiary
			TM Pleistocene
		 */
		String text = getFirstValue(BIOSISFields.GEOGRAPHIC_AREA);
		if (text != null)
		{
			String[] rows = text.split("\\/");
			for (String row: rows) 
				areas.add(row);
		}
		return areas;
	}

	public List<String> getMiscDescriptors() {
		List<String> miscDescs = new ArrayList<String>();
		String miscDescString = getFirstValue(BIOSISFields.MISC_DESCRIPTOR);
		if (miscDescString != null)
		{
			String[] descs = miscDescString.split(",");
			for (String desc: descs)
			{
				miscDescs.add(desc.trim());
			}
		}
		return miscDescs;
	}



	
	protected BIOSISRecord(Map<String, List<String>> fieldMap)
	{
		this.fieldMap = fieldMap;
	}
	
	public static void main(String[] args) throws Exception
	{
		BufferedReader br = new BufferedReader(new FileReader("/Users/cwillis/dev/mrc/workspace/losee/output/dryad/650/PREV200100292450.txt"));

		//BufferedReader br = new BufferedReader(new FileReader("/Users/cwillis/dev/mrc/journal_analysis/biosis_record.txt"));
		String line;
		String text = "";
		while ((line = br.readLine()) != null)
			text += line + "\n";
		br.close();

		BIOSISRecord record = BIOSISRecord.parse(text);
		List<String> c = record.getMajorConcepts();
		List<String[]> cc = record.getConceptCodes();
		List<String> md = record.getMiscDescriptors();
		//List<BIOSISTaxonomicData> td = record.getTaxonData();
		//System.out.println(td);
	}
	
	public static BIOSISRecord parse(File file) throws Exception {
		BufferedReader br = new BufferedReader(new FileReader(file));
		String line;
		String text = "";
		while ((line = br.readLine()) != null)
			text += line + "\n";
		br.close();
		return parse(text);
	}
	
	public static BIOSISRecord parse(String text) 
	{
		Map<String, List<String>> fieldMap = new HashMap<String, List<String>>();
		
		String[] lines = text.split("\\\n");
		String lastTag = null;
		String lastValue = null;
		for (String line: lines) 
		{
			if (line.length() == 0)
				continue;
			String fieldTag = line.substring(0, 2);
			String fieldValue = line.substring(2, line.length());
			
			if (fieldTag.equals("  "))
			{
				lastValue += " " + fieldValue;
			}
			else
			{
				if (lastTag != null)
				{
					List<String> valueList = fieldMap.get(lastTag);
					if (valueList == null)
						valueList = new ArrayList<String>();
					valueList.add(lastValue.trim());
					lastValue = "";
					fieldMap.put(lastTag, valueList);
				}
				
				lastTag = fieldTag;
				lastValue = fieldValue;
				
				if (fieldTag.equals(BIOSISFields.END_OF_RECORD.getFieldName()))
					break;
			}
			
		}
		return new BIOSISRecord(fieldMap);
	}
}
